<script setup lang="ts">
import {
  Moon,
  Sunny,
} from '@element-plus/icons-vue'
import { bus } from '@pkgs/utils'
import {
  useDark,
  useToggle,
} from '@vueuse/core'

const isDark = useDark()

const value = ref(isDark.value)

async function toggleDarkMode({
  clientX,
  clientY,
}: any) {
  function handler() {
    const toggleDark = useToggle(isDark)
    toggleDark()
    bus.emit('switch-dark-mode')
  }

  if (!document.startViewTransition) {
    return handler()
  }

  const clipPath = [
    `circle(0px at ${clientX}px ${clientY}px)`,
    `circle(${Math.hypot(
      Math.max(clientX, window.innerWidth - clientX),
      Math.max(clientY, window.innerHeight - clientY),
    )}px at ${clientX}px ${clientY}px)`,
  ]

  await document.startViewTransition(handler).ready

  document.documentElement.animate(
    { clipPath: isDark.value ? clipPath : clipPath.reverse() },
    {
      duration: 500,
      easing: 'ease-in',
      pseudoElement: `::view-transition-${isDark.value ? 'new' : 'old'}(root)`,
    },
  )
}

</script>

<template>
  <ElSwitch
    v-model="value"
    inline-prompt
    :active-icon="Sunny"
    :inactive-icon="Moon"
    @click="toggleDarkMode"
  />
</template>
